import 'package:get/get.dart';
import 'package:pornhub_app/components/diolog/dialog.dart';
import 'package:pornhub_app/components/diolog/loading/loading_view.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/mine/points_redemption_model.dart';
import 'package:pornhub_app/model/mine/signIn_mission_model.dart';
import 'package:pornhub_app/routes/routes.dart';
import 'package:pornhub_app/utils/logger.dart';
import 'package:pornhub_app/views/main/controllers/main_controller.dart';

import '../share_page_controller.dart';

class WelfarePageController extends GetxController {
  RxList<SigninMissionModel> missions = <SigninMissionModel>[].obs;
  Rx<PointsRedemptionModel> exchangeIntegral = PointsRedemptionModel().obs;
  RxList<PrizeList> prizes = <PrizeList>[].obs;

  @override
  void onInit() {
    super.onInit();
    initData();
  }

  initData() {
    postCheckIn();
    initMissions();
    _getUserExchangeIntegral();
  }

  /// 签到
  Future<bool> postCheckIn() async {
    try {
      await httpInstance.post(
        url: 'signIn/checkin',
      );
      initMissions();
      return true;
    } catch (e) {
      return false;
    }
  }

  ///获取任务列表
  void initMissions() async {
    try {
      List<SigninMissionModel>? result = await httpInstance.get(
        url: 'signIn/missionList',
        complete: SigninMissionModel.fromJson,
      );

      if (result != null && result.isNotEmpty) {
        missions.value = result;
      }
    } catch (e) {
      logger.e(e);
    }
  }

  startMissions(SigninMissionModel model) {
    if (model.status == 3) {
      showToast('任务已经完成啦');
      return;
    }
    if (model.status == 2) {
      getIntegral(model.missionId ?? 0);
    } else {
      /// 点击评论回复 跳转 社区页面
      if (model.missionType == 1 || model.missionType == 3) {
        Get.back();
        Get.find<MainController>().currentIndex.value = 3;
        return;
      }

      /// 点击分享  跳转 分享
      if (model.missionType == 2) {
        Get.find<SharePageController>().switchTab(0);
        // Get.toShare();
        return;
      }

      /// 点击首充  跳转 充值页面
      if (model.missionType == 4) {
        Get.offNamed(Routes.vip);
        return;
      }

      /// 点击购买金币视频 跳转 视频
      if (model.missionType == 5) {
        Get.back();
        Get.find<MainController>().currentIndex.value = 2;
        return;
      }

      /// 点击签到
      if (model.missionType == 6) {
        ///因为进来是自动签到，所以不用管
        return;
      }
    }
  }

  ///领取积分
  Future getIntegral(int missionId) async {
    try {
      await LoadingView.singleton.wrap(
        context: Get.context!,
        asyncFunction: () async {
          await httpInstance.post(
            url: 'signIn/receiveIntegral',
            body: {"id": missionId},
          );
          showToast("领取成功");
          initMissions();
          _getUserExchangeIntegral();
        },
      );
    } catch (e) {
      logger.e(e);
    }
  }

  bool _isFetchIng = false;

  void getMissionIntegral(int missionId) async {
    if (_isFetchIng) {
      return;
    }
    try {
      _isFetchIng = true;
      await LoadingView.singleton.wrap(
        context: Get.context!,
        asyncFunction: () async {
          await httpInstance.post(
            url: 'signIn/receiveIntegral',
            body: {"id": missionId},
          );
          showToast("领取成功");
          initMissions();
        },
      );
    } catch (e) {
      logger.e(e);
    } finally {
      _isExchangeIng = false;
    }
  }

  ///获取积分兑换列表
  Future _getUserExchangeIntegral() async {
    try {
      final result = await httpInstance.get<PointsRedemptionModel>(
        url: 'signIn/userExchangeIntegralPrizes',
        complete: PointsRedemptionModel.fromJson,
      );
      if (result is PointsRedemptionModel) {
        exchangeIntegral.value = result;
        if (result.prizeList != null && result.prizeList!.isNotEmpty) {
          prizes.assignAll(result.prizeList!);
        }
      }
    } catch (e) {
      logger.e(e);
    }
  }

  bool _isExchangeIng = false;

  void exChangePrize(PrizeList prize) async {
    if (_isExchangeIng) {
      return;
    }

    if ((exchangeIntegral.value.integral ?? 0) < prize.needIntegral!) {
      showToast("您的积分不足~");
      return;
    }
    try {
      _isExchangeIng = true;

      await LoadingView.singleton.wrap(
        context: Get.context!,
        asyncFunction: () async {
          await httpInstance.post(url: 'signIn/exchange', body: {
            "prizeId": prize.prizeId,
          });
          showToast("兑换成功");
          _getUserExchangeIntegral();
        },
      );
    } catch (e) {
      logger.e(e);
    } finally {
      _isExchangeIng = false;
    }
  }
}
